package com.kvest.multiframe_test;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.kvest.multiframe_test.fragment.ContentFragment;
import com.kvest.multiframe_test.fragment.HeadersFragment;

public class MultiframeTestActivity extends FragmentActivity implements HeadersFragment.OnItemSelectedListener {
    private static final String SELECTED_ITEM_KEY = "selected_item";
    private int selectedItem;
    private boolean innerDetails;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        selectedItem = 0;
        if (savedInstanceState != null) {
            this.selectedItem = savedInstanceState.getInt(SELECTED_ITEM_KEY);
        }
        innerDetails = (findViewById(R.id.content_container) != null);
        if (innerDetails) {
            showDetails(selectedItem);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(SELECTED_ITEM_KEY, selectedItem);
    }

    @Override
    public void onItemSelected(int id) {
        selectedItem = id;
        showDetails(selectedItem);
    }

    private void showDetails(int id) {
        if (innerDetails) {
            ContentFragment fragment = (ContentFragment) getSupportFragmentManager().findFragmentById(R.id.content_container);
            if (fragment == null || fragment.getPosition() != id) {
                getSupportFragmentManager().beginTransaction().replace(R.id.content_container,
                                                                        ContentFragment.newInstance(id)).commit();
            }
        } else {
            Intent intent = new Intent(getApplicationContext(), ContentActivity.class);
            intent.putExtra(ContentActivity.SELECTED_EXTRA, id);

            startActivity(intent);
        }
    }
}
